#!/bin/bash
#
# mapcheck - check map file to see if sections overflowed.
#
# The 6809 linker does not check to see if more objects are placed into
# a section than it can hold, because only a base address is given --
# there is no specified size.  Here, we scan the map file and compare
# the final length of each section to its predetermined maximum size,
# using a series of shell commands.
#
# If any section overflows, it returns nonzero and the build will halt.
#
# If any section is more than 95% full, a warning is printed but the
# build continues.  This allows some time for handling how to reorganize
# things before it becomes critical.
#

if [ "$1" = "" ]; then
	mapfile=`find build -name "*.map"`
else
	mapfile=$1
fi

checkpage ()
{
	section=$1; shift
	addr=$1; shift
	sz=`grep " l_${section}" ${mapfile} | awk '{print $1}'`
	max=$(($addr));
	used=$((0x$sz));
	avail=$(($max - 0x$sz));
	percent_used=$(( $used * 100 / $max ));
	dots=$(( $percent_used / 4 ));

	printf "%-10.10s" ${section}

	for (( i=0 ; $i < $dots ; i++ )); do
		echo -n "X"
	done
	for (( i=$dots+1 ; $i < 25 ; i++ )); do
		echo -n "."
	done

	if [ "$used" -gt "$max" ]; then
		echo "  error: overflow ($*)"
		return 1
	fi
	if [ "$percent_used" -gt 95 ]; then
		echo -n "  warning: $percent_used% full"
	fi

	if [ $1 ]; then
	   echo "   ($*)"
	else
		echo ""
	fi
	return 0
}

make -j1 areainfo | grep 0x | while read x; do
	checkpage $x || exit 1
done || exit 1
checkpage ".text" "0x8000" || exit 1;
